package cn._2dland.servlet;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TudouServlet extends HttpServlet {
	private static final long serialVersionUID = 3142026285156250877L;
	private static final String TUDOU_VIDEO_URL = " http://www.tudou.com/programs/view/";
	private static final String TUDOU_INFO_URL = "http://v2.tudou.com/v2/cdn?safekey=YouNeverKnowThat&id=";

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String vid = req.getParameter("vid");
		if(vid == null){
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		String url = TUDOU_VIDEO_URL + vid + "/";
		try{
			String html = getHTML(url);
			Pattern p = Pattern.compile("var iid = \\d+\\n");
			Matcher m = p.matcher(html);
			String iid = m.find() ? html.substring(m.start() + 10, m.end() - 1) : null;
			if(iid == null) throw new Exception("iid not found!");

			Random rnd = new Random();
			url = TUDOU_INFO_URL + iid + "&noCache=" + rnd.nextInt(10000);
			resp.setHeader("Location", url);
			resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		}
		catch (Exception e) {
			e.printStackTrace();
			resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}

	private String getHTML(String url) throws Exception {
		URL u = new URL(url);
		HttpURLConnection conn = (HttpURLConnection)u.openConnection();
		conn.setDoInput(true);
		conn.connect();

		int respCode = conn.getResponseCode();
		if(respCode != HttpURLConnection.HTTP_OK)
			throw new Exception("connect failed: " + respCode);

		StringBuffer strBuff = new StringBuffer();
		InputStreamReader isr = new InputStreamReader(conn.getInputStream());
		char[] cbuf = new char[32];
		int len = 0;
		do{
			strBuff.append(cbuf, 0, len);
			len = isr.read(cbuf);
		}while(len>=0);
		isr.close();
		conn.disconnect();

		return strBuff.toString();
	}
}
